<template>
  <div>
    <i-row style="height: 50px;">
      <i-col span="16">
        <i-input style="width: 300px;" placeholder="输入学生姓名进行检索" v-model="searchKey" @on-enter="search"></i-input>
        <i-button type="primary" @click="search">检索</i-button>
      </i-col>
      <i-col span="4">
        <i-button type="primary" @click="showAddClassHourDialog" style="width: 85%" :disabled="!hasSelection">
          追加课时
        </i-button>
      </i-col>
      <i-col span="4">
        <i-button type="primary" @click="showTransferClassDialog" style="width: 85%" :disabled="!hasSelection">
          安排班级
        </i-button>
      </i-col>
    </i-row>
    <i-row>
      <i-col span="24">
        <i-table border height="600" :columns="columns" :data="classHours" @on-selection-change="computeSelection"></i-table>
      </i-col>
    </i-row>

    <i-modal ref="addClassHourDialog" v-model="addClassHourDialogShowing" :title="addClassHourDialogTitle" @on-ok="okAddClassHourDialog" :loading="true">
      <i-form ref="addClassHourForm" :model="addClassHourEditModel" :label-width="80" :rules="addClassHourValidate">
        <i-form-item label="学号" prop="codeText">
          <i-input v-model="addClassHourEditModel.codeText" disabled></i-input>
        </i-form-item>
        <i-form-item label="姓名" prop="nameText">
          <i-input v-model="addClassHourEditModel.nameText" disabled></i-input>
        </i-form-item>
        <i-form-item label="追加课时" prop="classHour">
          <i-input-number v-model="addClassHourEditModel.classHour" :min="-20000" :max="20000" :step="2" @on-change="computeClassTime"></i-input-number>
          /
          <i-input-number v-model="addClassHourEditModel.classTime" :min="-10000" :max="10000" @on-change="computeClassHour"></i-input-number>
        </i-form-item>
        <i-form-item label="课时费用" prop="cost">
          <i-input-number v-model="addClassHourEditModel.cost" :min="-999999.99" :max="999999.99" :step="100"></i-input-number>
        </i-form-item>
      </i-form>
    </i-modal>

    <i-modal ref="transferClassDialog" v-model="transferClassDialogShowing" :title="transferClassDialogTitle" @on-ok="okTransferClassDialog" :loading="true">
      <i-form ref="transferClassForm" :model="transferClassEditModel" :label-width="80" :rules="transferClassValidate">
        <i-form-item label="学号" prop="codeText">
          <i-input v-model="transferClassEditModel.codeText" disabled></i-input>
        </i-form-item>
        <i-form-item label="姓名" prop="nameText">
          <i-input v-model="transferClassEditModel.nameText" disabled></i-input>
        </i-form-item>
        <i-form-item label="上课日期" prop="startDate">
          <i-date-picker type="date" v-model="transferClassEditModel.startDate"></i-date-picker>
        </i-form-item>
        <i-form-item label="班级编号" prop="classNum">
          <i-input-number :max="255" :min="0" v-model="transferClassEditModel.classNum"></i-input-number>
        </i-form-item>
      </i-form>
    </i-modal>
  </div>
</template>

<script>
import common from "@/common";
import HistoryRow from "@/components/class-hour-history-row";

export default {
  name: "student-management",
  components: {
    HistoryRow
  },
  data: function() {
    return {
      searchKey: "",
      selection: [],
      columns: [
        {
          type: "expand",
          width: 60,
          render: (h, params) => {
            return h(HistoryRow, {
              props: {
                studentId: params.row.id
              }
            });
          }
        },
        {
          type: "selection",
          align: "center",
          width: 60
        },
        {
          title: "学号",
          key: "code"
        },
        {
          title: "姓名",
          key: "name"
        },
        {
          title: "总课时",
          align: "center",
          width: 150,
          render: (h, params) => {
            return h("span", this.formatClassHour(params.row.totalClassHour));
          }
        },
        {
          title: "剩余课时",
          align: "center",
          width: 150,
          render: (h, params) => {
            const remainClassHour =
              params.row.totalClassHour - params.row.usedClassHour;
            return h(
              "div",
              {
                class: {
                  "remain-class-hour-prompt": remainClassHour <= 8,
                  "remain-class-hour-leak": remainClassHour <= 4
                }
              },
              this.formatClassHour(remainClassHour)
            );
          }
        },
        {
          title: "班级安排",
          width: 160,
          render: (h, params) => {
            return h(
              "span",
              this.formatStartDate(params.row.startDate, params.row.classNum)
            );
          }
        },
        {
          title: "缴费金额",
          key: "totalCost",
          width: 150,
          render: (h, params) => {
            return this.formatCost(params.row.totalCost);
          }
        }
      ],
      classHours: [],
      addClassHourDialogShowing: false,
      transferClassDialogShowing: false,
      addClassHourDialogTitle: "",
      transferClassDialogTitle: "",
      addClassHourEditModel: {},
      transferClassEditModel: {},
      addClassHourValidate: {
        classHour: [
          {
            required: true,
            type: "integer",
            message: "请输入有效的课时（整数，最大20000）。"
          }
        ],
        cost: [
          {
            required: true,
            type: "number",
            message: "请输入有效的课时费用（最大999999.99）。"
          }
        ]
      },
      transferClassValidate: {
        startDate: [
          {
            required: true,
            type: "date",
            message: "请输入上课日期。",
            trigger: "blur"
          }
        ],
        classNum: [
          {
            required: true,
            type: "number",
            message: "请输入有效的班级编号（0-255）。"
          }
        ]
      }
    };
  },
  created() {
    this.axios.get("/class-hours/search").then(response => {
      this.classHours = response.data;
    });
  },
  computed: {
    hasSelection() {
      return this.selection.length > 0;
    }
  },
  methods: {
    search() {
      this.axios
        .get("/class-hours/search", {
          params: {
            name: this.searchKey
          }
        })
        .then(response => {
          this.classHours = response.data;
          this.selection = [];
        });
    },
    computeSelection(selection) {
      this.selection = selection;
    },
    computeClassHour() {
      this.addClassHourEditModel.classHour =
        this.addClassHourEditModel.classTime * 2;
    },
    computeClassTime() {
      this.addClassHourEditModel.classTime =
        this.addClassHourEditModel.classHour / 2;
    },
    showAddClassHourDialog() {
      this.$refs["addClassHourForm"].resetFields();

      this.addClassHourDialogTitle =
        "追加课时" + (this.selection.length > 1 ? "（多个学生）" : "");

      let codeText = "";
      let nameText = "";
      for (let index in this.selection) {
        codeText += (codeText === "" ? "" : ",") + this.selection[index].code;
        nameText += (nameText === "" ? "" : ",") + this.selection[index].name;
      }
      this.addClassHourEditModel = {
        codeText: codeText,
        nameText: nameText,
        classHour: 0,
        classTime: 0,
        cost: 0
      };

      this.addClassHourDialogShowing = true;
    },
    showTransferClassDialog() {
      this.$refs["transferClassForm"].resetFields();

      this.transferClassDialogTitle =
        "安排班级" + (this.selection.length > 1 ? "（多个学生）" : "");

      let codeText = "";
      let nameText = "";
      for (let index in this.selection) {
        codeText += (codeText === "" ? "" : ",") + this.selection[index].code;
        nameText += (nameText === "" ? "" : ",") + this.selection[index].name;
      }
      this.transferClassEditModel = {
        codeText: codeText,
        nameText: nameText,
        startDate: new Date(),
        classNum: 1
      };

      this.transferClassDialogShowing = true;
    },
    okAddClassHourDialog() {
      this.$refs["addClassHourForm"].validate(valid => {
        if (valid) {
          this.doAddClassHourPost();
        } else {
          this.$refs["addClassHourDialog"].buttonLoading = false;
        }
      });
    },
    okTransferClassDialog() {
      this.$refs["transferClassForm"].validate(valid => {
        if (valid) {
          this.doTransferClassPost();
        } else {
          this.$refs["transferClassDialog"].buttonLoading = false;
        }
      });
    },
    doAddClassHourPost() {
      let url = "/class-hours";
      let data = null;
      if (this.selection.length > 1) {
        url += "/all";
        data = [];
        for (let index in this.selection) {
          data[index] = this.buildAddClassHourPostData(index);
        }
      } else {
        data = this.buildAddClassHourPostData(0);
      }

      this.postAddClassHourDate(url, data);
    },
    doTransferClassPost() {
      let url = "/class-arranges";
      let data = null;
      if (this.selection.length > 1) {
        url += "/all";
        data = [];
        for (let index in this.selection) {
          data[index] = this.buildTransferClassPostData(index);
        }
      } else {
        data = this.buildTransferClassPostData(0);
      }

      this.postTransferClassDate(url, data);
    },
    postAddClassHourDate(url, data) {
      this.axios.post(url, data).then(response => {
        if (response.code === 0) {
          this.$Message.success("追加课时成功。");
          this.addClassHourDialogShowing = false;
          this.search();
        } else {
          this.$Message.error("追加课时失败。" + response.message);
          this.$refs["addClassHourDialog"].buttonLoading = false;
        }
      });
    },
    postTransferClassDate(url, data) {
      this.axios.post(url, data).then(response => {
        if (response.code === 0) {
          this.$Message.success("安排班级成功。");
          this.transferClassDialogShowing = false;
          this.search();
        } else {
          this.$Message.error("安排班级失败。" + response.message);
          this.$refs["transferClassDialog"].buttonLoading = false;
        }
      });
    },
    buildAddClassHourPostData(index) {
      return {
        studentId: this.selection[index].id,
        classHour: this.addClassHourEditModel.classHour,
        cost: this.addClassHourEditModel.cost,
        operateDate: new Date()
      };
    },
    buildTransferClassPostData(index) {
      return {
        studentId: this.selection[index].id,
        startDate: this.transferClassEditModel.startDate,
        classNum: this.transferClassEditModel.classNum
      };
    },
    formatClassHour(classHour) {
      return common.formatClassHour(classHour);
    },
    formatStartDate(startDate, classNum) {
      if (startDate && classNum) {
        return common.formatWeekDate(startDate) + " #" + classNum;
      } else {
        return "-";
      }
    },
    formatCost(cost) {
      return common.formatCost(cost);
    }
  }
};
</script>

<style>
/*TODO: How to change to scoped*/
.ivu-table .remain-class-hour-prompt {
  color: #fff;
  background-color: #ff9900;
}

.ivu-table .remain-class-hour-leak {
  color: #fff;
  background-color: #ed3f14;
}
</style>
